using System;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Quartz.Impl;
using Quartz;
namespace CSharp.Basic.Learn.作业调度.作业持久化
{
  /// <summary>
  /// refs: https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/job-stores.html
  /// </summary>
  public static class JobSchedulerWithMysql
  {
    public async static Task RunAsync()
    {
      try
      {
        //配置Quartz以使用JobStoreTx
        //配置AdoJobStore以使用DriverDelegate
        //使用表前缀配置AdoJobStore
        //使用要使用的数据源的名称配置AdoJobStore
        //设置数据源的连接字符串和数据库提供程序
        //配置AdoJobStore以将字符串用作JobDataMap值（推荐）
        var props = new NameValueCollection{
          {"quartz.serializer.type","json"},
          {"quartz.jobStore.type","Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"},
          {"quartz.jobStore.driverDelegateType","Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz"},
          {"quartz.jobStore.tablePrefix","QRTZ_"},
          {"quartz.jobStore.dataSource","local"},
          {"quartz.dataSource.local.connectionString","Server=localhost;Database=local_db;Uid=root;Pwd=Jiang.2527786719"},
          {"quartz.dataSource.local.provider","MySql"},
          {"quartz.jobStore.useProperties","true"}
      };

        var factory = new StdSchedulerFactory(props);
        var scheduler = await factory.GetScheduler();
        await scheduler.Start();
        //设置JobDetail信息
        var jobDetail = JobBuilder.Create<HelloMySqlJob>()
                                  .WithIdentity("mysql_job_key")
                                  .Build();
        //添加Trigger信息
        var trigger = TriggerBuilder.Create()
                                    .WithIdentity("mysql_trigger_key")
                                    .WithSimpleSchedule(x =>
                                    {
                                      x.WithIntervalInSeconds(10);
                                      x.WithRepeatCount(50);
                                    })
                                    .Build();
        //告诉调度器使用指定的Trigger执行指定的Job
        await scheduler.ScheduleJob(jobDetail, trigger);

      }
      catch (SchedulerException ex)
      {
        Console.WriteLine(ex);
      }

    }
  }
}
